package com.atguigu.gmall.activity.controller;

import com.atguigu.gmall.activity.service.SeckillGoodsService;
import com.atguigu.gmall.activity.util.CacheHelper;
import com.atguigu.gmall.activity.util.DateUtil;
import com.atguigu.gmall.common.constant.MqConst;
import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.result.ResultCodeEnum;
import com.atguigu.gmall.common.service.RabbitService;
import com.atguigu.gmall.common.util.AuthContextHolder;
import com.atguigu.gmall.common.util.MD5;
import com.atguigu.gmall.model.activity.OrderRecode;
import com.atguigu.gmall.model.activity.SeckillGoods;
import com.atguigu.gmall.model.activity.UserRecode;
import com.atguigu.gmall.model.order.OrderDetail;
import com.atguigu.gmall.model.order.OrderInfo;
import com.atguigu.gmall.model.user.UserAddress;
import com.atguigu.gmall.order.client.OrderFeignClient;
import com.atguigu.gmall.user.client.UserFeignClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@RestController
@RequestMapping("/api/activity/seckill")
public class SeckillGoodsApiController {

    @Autowired
    private SeckillGoodsService seckillGoodsService;

    @Autowired
    private RabbitService rabbitService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private UserFeignClient userFeignClient;

    @Autowired
    private OrderFeignClient orderFeignClient;

    /**
     * 查询秒杀商品列表
     *
     * @return
     */
    @GetMapping("/findAll")
    public Result findAll() {
        List<SeckillGoods> seckillGoodsList = seckillGoodsService.findAll();
        return Result.ok(seckillGoodsList);
    }

    /**
     * 根据秒杀商品Id查询秒杀商品的详情
     *
     * @param skuId
     * @return
     */
    @GetMapping("/getSeckillGoods/{skuId}")
    public Result getSeckillGoods(@PathVariable Long skuId) {
        SeckillGoods seckillGoods = seckillGoodsService.getSeckillGoods(skuId);
        return Result.ok(seckillGoods);
    }

    /**
     * 获取秒杀码
     * item.html.queue().seckill.getSeckillSkuIdStr()：/api/activity/seckill/auth/getSeckillSkuIdStr/{skuId}
     * 秒杀码 = 用户Id + MD5 加密
     * 商品秒杀开始之后 && 秒杀结束之前 点击立即抢购 获取秒杀码
     *
     * @param skuId
     * @param request
     * @return
     */
    @GetMapping("auth/getSeckillSkuIdStr/{skuId}")
    public Result getSeckillSkuIdStr(@PathVariable Long skuId, HttpServletRequest request) {
        // 获取用户Id
        String userId = AuthContextHolder.getUserId(request);

        if (userId != null) {
            // 获取当前秒杀的商品
            SeckillGoods seckillGoods = seckillGoodsService.getSeckillGoods(skuId);

            // 获取当前系统时间
            Date currentTime = new Date();

            // 获取秒杀码的时机：商品秒杀开始之后 && 秒杀结束之前
            if (DateUtil.dateCompare(seckillGoods.getStartTime(), currentTime)
                    && DateUtil.dateCompare(currentTime, seckillGoods.getEndTime())) {

                // 制作秒杀码
                String skuIdStr = MD5.encrypt(userId);

                // 返回秒杀码
                return Result.ok(skuIdStr);

            }
        }
        return Result.fail("抢购下单码失败");
    }

    /**
     * 秒杀下单
     * /api/activity/seckill/auth/seckillOrder/{skuId}?skuIdStr=skuIdStr
     *
     * @param skuId
     * @param request
     * @return
     */
    @PostMapping("auth/seckillOrder/{skuId}")
    public Result seckillOrder(@PathVariable Long skuId, HttpServletRequest request) {
        /*
            1 校验下单码
            2 校验状态位 state ：state=null=请求非法 | state=0=售罄 | state=1=允许抢购
            3 将秒杀用户加入消息队列
         */
        // 获取用户Id
        String userId = AuthContextHolder.getUserId(request);

        // 获取页面传递的秒杀码
        String skuIdStr = request.getParameter("skuIdStr");

        // 校验秒杀码
        if (!MD5.encrypt(userId).equals(skuIdStr)) {
            // 非法请求
            return Result.build(null, ResultCodeEnum.SECKILL_ILLEGAL);
        }

        // 获取状态位{状态位存储在Map中}
        String state = (String) CacheHelper.get(skuId.toString());
        // 校验状态码
        if (StringUtils.isEmpty(state)) {
            // 非法请求
            return Result.build(null, ResultCodeEnum.SECKILL_ILLEGAL);
        }
        if ("1".equals(state)) {// 允许抢购

            // 记录当前秒杀的用户信息
            UserRecode userRecode = new UserRecode();
            userRecode.setSkuId(skuId);
            userRecode.setUserId(userId);

            // 将秒杀用户加入消息队列
            rabbitService.sendMessage(
                    MqConst.EXCHANGE_DIRECT_SECKILL_USER,
                    MqConst.ROUTING_SECKILL_USER,
                    userRecode);

        } else {
            // 已售罄
            return Result.build(null, ResultCodeEnum.SECKILL_FINISH);
        }
        return Result.ok();
    }

    /**
     * 秒杀确认订单
     * <a href="/seckill/trade.html" target="_blank">去下单</a>
     *
     * @return
     */
    @GetMapping("auth/trade")
    public Result trade(HttpServletRequest request) {

        // 获取用户Id
        String userId = AuthContextHolder.getUserId(request);

        // 从缓存获取临时订单数据
        OrderRecode orderRecode = (OrderRecode) redisTemplate.boundHashOps(RedisConst.SECKILL_ORDERS).get(userId);

        if (orderRecode == null){
            return Result.fail().message("非法操作");
        }

        // 获取用户收货地址
        List<UserAddress> userAddressList = userFeignClient.findUserAddressListByUserId(userId);

        // 获取用户秒杀的是哪个商品
        SeckillGoods seckillGoods = orderRecode.getSeckillGoods();

        // 创建一个订单明细
        OrderDetail orderDetail = new OrderDetail();
        orderDetail.setSkuId(seckillGoods.getSkuId());
        orderDetail.setSkuName(seckillGoods.getSkuName());
        orderDetail.setImgUrl(seckillGoods.getSkuDefaultImg());
        orderDetail.setSkuNum(orderRecode.getNum());
        orderDetail.setOrderPrice(seckillGoods.getCostPrice());

        // 将 orderDetail 放入一个集合 用于计算总金额
        ArrayList<OrderDetail> orderDetailList = new ArrayList<>();
        orderDetailList.add(orderDetail);

        // 创建一个 orderInfo
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setOrderDetailList(orderDetailList);
        // 计算总金额
        orderInfo.sumTotalAmount();

        // 创建 Map 保存数据
        Map<String, Object> result = new HashMap<>();
        result.put("userAddressList", userAddressList);
        result.put("detailArrayList", orderDetailList);
        result.put("totalAmount", orderInfo.getTotalAmount());

        return Result.ok(result);
    }

    /**
     * 提交秒杀订单
     * url: this.api_name + '/auth/submitOrder'
     */
    public Result submitOrder(HttpServletRequest request){
        String userId = AuthContextHolder.getUserId(request);


        return Result.ok();
    }
}
